package com.ccrfid.rmc6.resource.dbg;

import com.ccrfid.rmc6.appconfig.exception.pojo.AppException;
import com.ccrfid.rmc6.entity.device.LocatorEntity;
import com.ccrfid.rmc6.entity.personnel.PersonnelEntity;
import com.ccrfid.rmc6.entity.poi.PoiLocationEntity;
import com.ccrfid.rmc6.pojo.dto.OutlineDto;
import com.ccrfid.rmc6.service.business.chongqing.baodeng.BaodengDataService;
import com.ccrfid.rmc6.service.business.chongqing.baodeng.pojo.MsgPatrol;
import com.ccrfid.rmc6.service.business.chongqing.baodeng.pojo.PatrolScheduleDto;
import com.ccrfid.rmc6.service.device.LocatorService;
import com.ccrfid.rmc6.service.personnel.PersonnelService;
import com.ccrfid.rmc6.service.poi.PoiService;
import com.ccrfid.rmc6.service.sys.KeyValueService;
import com.ccrfid.rmc6.service.video.HikArtemisService;
import com.ccrfid.rmc6.util.DateUtil;
import com.ccrfid.rmc6.util.JsonUtil;
import com.ccrfid.rmc6.ws.c5.cardreader.pojo.UploadCardRequest;
import com.ccrfid.rmc6.ws.c5.videosync.VideoSyncClient;
import com.ccrfid.rmc6.ws.c5.videosync.pojo.ListVideoRequest;
import com.ccrfid.rmc6.ws.c5.videosync.pojo.VideoRes;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.List;

@Path("test")
@Produces(MediaType.APPLICATION_JSON)
public class TestResource {
    private static final Logger logger = LoggerFactory.getLogger(TestResource.class);
    @Context
    private UriInfo uriInfo;
    @Context
    private HttpServletRequest httpServletRequest;
    @Context
    private HttpServletResponse httpServletResponse;
    @Context
    SecurityContext securityContext;
    @Autowired
    private KeyValueService keyValueService;
    @Autowired
    private PersonnelService personnelService;
    @Autowired
    private VideoSyncClient videoSyncClient;
    @Autowired
    private PoiService poiService;
    @Autowired
    private LocatorService locatorService;
    @Autowired
    private BaodengDataService baodengDataService;

    @GET
    @Path("GetSchedule")
    public List<PatrolScheduleDto> getPatrolSchedule(@QueryParam("date") String date) {
        List<PatrolScheduleDto> list = baodengDataService.getPatrolSchedule(date);
        logger.debug("PatrolSchedule list: {}", JsonUtil.INSTANCE.writeValueAsString(list));
        return list;
    }

    @GET
    @Path("postPatrol")
    public String postMsgPatrol() {
        MsgPatrol msgPatrol = new MsgPatrol();
        msgPatrol.setPoliceName("zhangsan");
        msgPatrol.setRoadId(1L);
        msgPatrol.setRoadName("roadname");
        msgPatrol.setPointCount(10);
        msgPatrol.setPatrolCount(11);
        msgPatrol.setStopTime(DateUtil.toDateTimeStr(new Timestamp(System.currentTimeMillis())));
        msgPatrol.setStartTime(DateUtil.toDateTimeStr(new Timestamp(System.currentTimeMillis())));
        baodengDataService.postMsgPatrol(msgPatrol);
        return "OK";
    }

    @GET
    @Path("sync/photo")
    public void syncPhoto() {
        List<PersonnelEntity> personnelEntities = personnelService.getPersonnelListByCardNumberNotNull();
        for (PersonnelEntity entity : personnelEntities) {
            String fp = "d:\\temp\\personnel_image\\ccms" + entity.getPersonnelSn() + ".png";
            updatePhoto(entity.getId(), fp);
        }
    }

    private void updatePhoto(Long personnelId, String filepath) {
        try {
            File file = new File(filepath);
            if (file.exists()) {
                java.nio.file.Path path = Paths.get(filepath);
                byte[] data = Files.readAllBytes(path);
                personnelService.updatePersonnelPhoto(personnelId, data);
                logger.info("**** save photo: {} - {}", personnelId, filepath);
            } else {
                java.nio.file.Path path = Paths.get("d:\\temp\\personnel_image\\ccms330282111201706260072.png");
                byte[] data = Files.readAllBytes(path);
                personnelService.updatePersonnelPhoto(personnelId, data);
                logger.info("**** save default photo: {} - {}", personnelId, filepath);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (AppException ex) {
            ex.printStackTrace();
        }
    }

    @GET
    @Path("point")
    public Point getPoint() throws ParseException {
        Point point = (Point) new WKTReader().read("POINT(100.123 200.321)");
        System.out.println(point.getX() + ", " + point.getY());
        Polygon polygon = (Polygon) new WKTReader().read("POLYGON((10 10, 30 10, 30 30, 10 30, 10 10))");
        Coordinate[] shellCoordinates = polygon.getCoordinates();
        for (Coordinate coordinate : shellCoordinates) {
            System.out.println(coordinate.x + " " + coordinate.y);
        }
        System.out.println(point.toString());
        System.out.println("xxx");
        System.out.println(point.toText());
        logger.info("getRemoteAddr: {}", httpServletRequest.getRemoteAddr());
        logger.info("getRemoteHost: {}", httpServletRequest.getRemoteHost());
        logger.info("getRemotePort: {}", httpServletRequest.getRemotePort());
        logger.info("getRemoteUser: {}", httpServletRequest.getRemoteUser());

        return point;
    }

    @GET
    @Path("point2")
    public Point getPoint2() {
        GeometryFactory gf = new GeometryFactory();
        Point point = gf.createPoint(new Coordinate(1.0, 2.2));
        System.out.println(point);
        return point;
    }

    @PUT
    @Path("point")
    @Consumes(MediaType.APPLICATION_JSON)
    public Point updatePoint(Point point) {
        System.out.println(point.toString());
        return point;
    }

    @GET
    @Path("polygon")
    public Polygon getPolygon() throws ParseException {
        Point point = (Point) new WKTReader().read("POINT(100.123 200.321)");
        System.out.println(point.getX() + ", " + point.getY());
        Polygon polygon = (Polygon) new WKTReader().read("POLYGON((10 10, 30 10, 30 30, 10 30, 10 10))");
        Coordinate[] shellCoordinates = polygon.getCoordinates();
        for (Coordinate coordinate : shellCoordinates) {
            System.out.println(coordinate.x + " " + coordinate.y);
        }
        System.out.println(polygon.toString());
        System.out.println(polygon.toText());

        return polygon;
    }

    @GET
    @Path("polygon2")
    public Polygon getPolygon2() {
        GeometryFactory gf = new GeometryFactory();
        Polygon polygon = gf.createPolygon(new Coordinate[]{
                new Coordinate(1.1, 1.1),
                new Coordinate(1.1, 2.2),
                new Coordinate(3.3, 2.2),
                new Coordinate(3.3, 1.1),
                new Coordinate(1.1, 1.1)
        });
        System.out.println(polygon);
        return polygon;
    }

    @PUT
    @Path("polygon")
    @Consumes(MediaType.APPLICATION_JSON)
    public Polygon updatePolygon(Polygon polygon) {
        System.out.println(polygon.toString());
        return polygon;
    }

    @GET
    @Path("outline/{id}")
    public OutlineDto getOutline(@PathParam("id") Long id) {
        return keyValueService.getOutline(id);
    }

    @PUT
    @Path("outline")
    @Consumes(MediaType.APPLICATION_JSON)
    public void saveOutline(OutlineDto entity) {
        keyValueService.saveOutline(entity);
    }

    @GET
    @Path("ws-client")
    public void testWsClient(@QueryParam("serviceUrl") String serviceUrl) {
        UploadCardRequest request = new UploadCardRequest();
        request.setCardIcNumber("111111111111111");
        request.setCardNumber(2222L);
        request.setCardReaderNumber("3333333333333");
        request.setIpAddrs("4.4.4.4");

        videoSyncClient.uploadCardRequestTest(serviceUrl, request);
    }

    @GET
    @Path("sync-video")
    public VideoRes[] testSyncVideo(@QueryParam("version") Integer version,
                                    @QueryParam("ip") String ip,
                                    @QueryParam("port") Integer port,
                                    @QueryParam("username") String username,
                                    @QueryParam("password") String password,
                                    @QueryParam("orgCode") String orgCode,
                                    @QueryParam("serviceUrl") String serviceUrl) {
        ListVideoRequest request = new ListVideoRequest();
        request.setiVersion(version);
        request.setcIp(ip);
        request.setiPort(port);
        request.setcUsername(username);
        request.setcPassword(password);
        request.setcOrgCode(orgCode);

        return videoSyncClient.listVideo(serviceUrl, request);
    }

    @GET
    @Path("locations-by-locator/{locatorAddress}")
    public List<PoiLocationEntity> getLocations(@PathParam("locatorAddress") Integer locatorAddress) {
        LocatorEntity locatorEntity = locatorService.getLocatorByLocatorAddress(locatorAddress);
        List<PoiLocationEntity> list = poiService.getLocationsByLocator(locatorEntity);
        System.out.println("**");
        ;
        System.out.println(JsonUtil.INSTANCE.writeValueAsString(locatorEntity));
        System.out.println(JsonUtil.INSTANCE.writeValueAsString(list));
        return list;
    }

    @Autowired
    private HikArtemisService hikArtemisService;

    @GET
    @Path("hik-artemis")
    public String hikArtemisTest() {

        logger.debug("** getAppSecret: {}", hikArtemisService.getAppSecret());

        logger.debug("** getAllRegions: {}", hikArtemisService.getAllRegions());

        logger.debug("** getAllCameras: {}", hikArtemisService.getAllCameras());

        logger.debug("** getSubRegions: {}", hikArtemisService.getSubRegions("b2170878755648108732a786f8ac5190"));

        logger.debug("** getSubCameras: {}", hikArtemisService.getSubCameras("a1d496650dd44ee7b66ab17f23e2d373"));

        logger.debug("** getPreviewURL: {}", hikArtemisService.getPreviewURL("2302e3e9690346b591531ab3318d91e2", "rtmp", 0, 0));

        logger.debug("** getPlaybackURL: {}", hikArtemisService.getPlaybackURL("2302e3e9690346b591531ab3318d91e2", "hls",
                "2019-11-27T10:00:00+08:00", "2019-11-27T11:00:00+08:00", 0));

        return "test finished.";
    }
}
